/*
 * marketsim-eclipsetrader
 *
 * Copyright (C) 2008-2011 Steve Phelps and John Cartlidge
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of
 * the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 */
package victria.marketsim.core;

import java.util.Properties;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;

public class BeanFactorySingleton {

	public static final String CONFIG_FILE = 
		"victria/marketsim/core/marketsim.xml";
	
	public static final String PROPERTIES_FILE =
		"marketsim.properties";

	protected static XmlBeanFactory beanFactory;

	static Logger logger = Logger.getLogger(BeanFactorySingleton.class);
	
	public static synchronized BeanFactory getBeanFactory() {
		if (beanFactory == null) {
			initialiseFactory();
		}
		return beanFactory;
	}
	
	public static synchronized void registerFactory(XmlBeanFactory beanFactory) {
		BeanFactorySingleton.beanFactory = beanFactory;
	}
	
	public static Object getBean(String id) {
		return getBeanFactory().getBean(id);
	}
	
	public static void initialiseFactory() {
		logger.debug("Initialising bean factory..");
		XmlBeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource(
				CONFIG_FILE));
		BeanFactorySingleton.registerFactory(beanFactory);
		PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
		// First look for config file in current directory
		Resource configLocation = new FileSystemResource(PROPERTIES_FILE);
		if (configLocation.exists()) {
			// Configure log4j with this file
			PropertyConfigurator.configure(PROPERTIES_FILE);
		} else {
			// If can't find it here then look on classpath
			configLocation = new ClassPathResource(PROPERTIES_FILE);
		} 
		ppc.setLocation(configLocation);
		ppc.postProcessBeanFactory(beanFactory);
		logger.debug("done.");
	}
}
